package com.cl.short_video_java.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.cl.short_video_java.common.Result;
import com.cl.short_video_java.service.CommonService;
import com.cl.short_video_java.service.SysSettingService;
import com.cl.short_video_java.util.RedisUtil;
import com.cl.short_video_java.web.FileController;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 付
 * @Date 2024-11-02 16:32
 * @Version 1.0
 * @description 通用业务类
 * @since 1.0
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
	@Resource
	private Producer producer;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	SysSettingService settingService;

	/**
	 * 获取验证码
	 *
	 * @return
	 */
	@Override
	public Map<String, String> captcha() {
		// 生成uuid
		String uuid = UUID.randomUUID().toString();
		// 生成验证码
		String code = producer.createText();
		System.out.println(code);
//		生成base64编码的图片验证码
		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpg", byteArrayOutputStream);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		String base64Img = "data:image/jpeg;base64," + Base64Encoder.encode(byteArrayOutputStream.toByteArray());

		// 把uuid和验证码存储到redis
		redisUtil.setEx(uuid, code, 30, TimeUnit.SECONDS);
		// 返回uuid和base64编码
		HashMap<String, String> map = new HashMap<>();
		map.put("uuid", uuid);
		map.put("base64Img", base64Img);
		return map;
	}

	@Override
	public String uploadImg(MultipartFile file) throws IOException {
		String sysImgServerUrl = settingService.getSysSettingByKey("sys_img_server_url");
		synchronized (FileController.class) {
			// 获取一个标志，防止文件重名被覆盖
			String flag = System.currentTimeMillis() + "";
			// 获取文件原名
			String filename = file.getOriginalFilename();
			StringBuilder path = new StringBuilder();
			// 图片压缩
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			Img.from(file.getInputStream())
					.scale(0.6F)// 缩小比例
					.setQuality(0.2) // 压缩比例
					.write(byteArrayOutputStream);
			try {
				// 判断是否存在这个文件夹，如果没有就创建
				if (FileUtil.isDirectory(sysImgServerUrl)) {
					FileUtil.mkdir(sysImgServerUrl);
				}
				// 写文件，将文件写入到指定的文件夹，文件的名称是：flag + 文件原始名称

				FileUtil.writeBytes(byteArrayOutputStream.toByteArray(), sysImgServerUrl + flag + "-" + filename);
				Thread.sleep(1L);
				// 这里就可以将flag存储到数据库中
				// 完整请求路径
				path.append("http://139.159.176.201:8088/image/" + flag + "-" + filename);
				log.info("path=====>", path);
			} catch (Exception e) {
				System.out.println();
				log.error("存放的文件地址：", sysImgServerUrl, "---生成的文件名", filename, "上传失败");
			}
			return path.toString();
		}
	}
}
